﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace UDP组播_02
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress ip = null;
            IPAddress[] ips = Dns.GetHostAddresses("");
            foreach (var v in ips)
            {
                if (v.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip = v;
                    break;
                }
            }

            IPEndPoint iep = new IPEndPoint(ip, 8002);
            string Addrstr = "224.0.0.6";
            IPAddress multicastAddress = IPAddress.Parse(Addrstr);
            Console.WriteLine("在端口{0}监听，加入的多播组为{1}", iep.Port, multicastAddress);
            UdpClient client = new UdpClient(iep);
            client.JoinMulticastGroup(multicastAddress);
            IPEndPoint remoteEp = null;
            var t1 = Task.Run(() => {
                while (true)
                {
                    var result = client.Receive(ref remoteEp);
                    Console.WriteLine("来自{0}:{1}", remoteEp, Encoding.Unicode.GetString(result));
                }
            });
            var t2 = Task.Run(() => {
                while (true)
                {
                    string str = Console.ReadLine();
                    byte[] bytes = Encoding.Unicode.GetBytes(str);

                    client.Send(bytes, bytes.Length, Addrstr, 8001);
                    client.Send(bytes, bytes.Length, Addrstr, 8002);
                    client.Send(bytes, bytes.Length, Addrstr, 8003);
                }
            });
            t1.Wait();
            t2.Wait();
        }
    }
}
